Root Zanli
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
home
/
o5t6x7pgljbm
/
public_html
/
admin
/
app
/
V2
/
Services
/
Filename :
TaskService.php
back
Copy
<?php namespace App\V2\Services; use App\Http\Controllers\Api\CommonController; use App\Libraries\Helpers; use App\Models\Group; use App\Models\Permission; use App\Models\PermissionUserEntity; use App\Models\ProductImage; use App\Models\Store; use App\Models\Task; use App\Models\TaskAssigned; use App\Models\TaskImage; use App\Models\TaskReviewAllowed; use App\Models\TaskSetting; use App\Models\TaskVisibility; use App\Models\User; use App\V2\Dtos\FilterTaskDTO; use App\V2\Dtos\GetTaskDTO; use App\V2\Dtos\TaskAssigneeFilterDTO; use App\V2\Dtos\TaskFilterDto; use App\V2\Repositories\TaskRepository; use Carbon\Carbon; use Exception; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Image; use Illuminate\Support\Str; /** * Contains the business logic for task related functionality */ class TaskService extends BaseService { private $taskRepository; private $tuitService; private $userActivityService; public function __construct() { $this->taskRepository = new TaskRepository(); $this->tuitService = new TUITService(); $this->userActivityService = new UserActivityService(); } public function getTasks(FilterTaskDTO $filter){ $tasks = $this->taskRepository->filterTasks($filter); $this->loadAdditionalInfo($tasks, $filter); return $tasks; } public function getDueSoonTasks(FilterTaskDTO $filter){ $today = Carbon::now(); $today_str = $today->format('Y-m-d'); $three_days_after = $today->addDays(3); $three_days_after_str = $three_days_after->format('Y-m-d'); $dueSoonTaskFilter = FilterTaskDTO::builder() ->copyFrom($filter) ->dueByGraterThan($today_str) ->dueByLessThan($three_days_after_str) ->build(); $tasks = $this->taskRepository->filterTasks($dueSoonTaskFilter); $this->loadAdditionalInfo($tasks, $filter); return $tasks; } public function getRecommendedTasks(FilterTaskDTO $filter){ $recommendedTaskFilter = FilterTaskDTO::builder() ->copyFrom($filter) ->shouldBeRecommended(true) ->build(); $tasks = $this->taskRepository->filterTasks($recommendedTaskFilter); $this->loadAdditionalInfo($tasks, $filter); return $tasks; } public function getRecurringTasks(FilterTaskDTO $filter){ $dueSoonTaskFilter = FilterTaskDTO::builder() ->copyFrom($filter) ->shouldBeRecurring(true) ->build(); $tasks = $this->taskRepository->filterTasks($dueSoonTaskFilter); $this->loadAdditionalInfo($tasks, $filter); return $tasks; } /** * returns list of tasks with following details, * regardless of if the task is present in the active group: * 1, Assignee Lists */ public function getTasksById(GetTaskDTO $getTaskDto){ $filter = FilterTaskDTO::builder() ->copyFrom($getTaskDto) ->taskIds($getTaskDto->getTaskIds()) ->getForGroupOrGlobal($getTaskDto->getForGroupOrGlobal()) ->shouldLoadAssigneeList(true) ->include_null_for_due_by(true) ->build(); $tasks = $this->taskRepository->filterTasks($filter); if(count($tasks)==0){ throw new Exception('could not find tasks by id', 404); } $this->loadAdditionalInfo($tasks, $filter); $tasks->each(function ($task) {$task->images;}); return $tasks; } /** * $task_details - basic task model details * $task_assignees_user_id_list - list of user_ids to whom task needs to be assigned * $task_images - list of task images * $task_settings_details - additions settings for the task * $task_visibility_details - additions details around task visibility * $task_review_permission_details - additional details around task review permissions * * Sends notifications to invitees */ public function createTask($currentUser, $task_details, $task_assignees_user_id_list, $task_images, $task_settings_details, $task_visibility_details, $task_review_permission_details, $currentGroup, $currentStore ){ //create task $task_details['uuid'] = Str::uuid()->toString();; $task = Task::create($task_details); //create task_settings $task_settings = TaskSetting::create(array_merge($task_settings_details, ['task_id' => $task->task_id])); //create task visibility settings $task_visibility_list = []; if(isset($task_visibility['entity_ids'])){ foreach($task_visibility['entity_ids'] AS $entity_id){ $task_visibility_list[] = ['task_settings_id' => $task_settings->task_settings_id, 'entity_type' => $task_visibility['entity_type'], 'entity_id' => $entity_id]; } } $task_visibility = TaskVisibility::insert($task_visibility_list); $task_review_allowed_to_type_arr = isset($task_settings_details['task_review_allowed_to_type_arr']) ? $task_settings_details['task_review_allowed_to_type_arr'] : ['PARENTS_OR_FOSTER_AGENT']; $this->saveTaskReviewAllowed($task->task_id, $task_settings->task_settings_id, $task_review_allowed_to_type_arr); //create task review permission details $task_review_permission = Permission::where('name', 'TASK_REVIEW')->first(); $task_review_permission_id =$task_review_permission->id; $permission_user_entity_list = []; if(isset($task_review_permission_details['entity_ids'])){ foreach($task_review_permission_details['entity_ids'] AS $entity_id){ $permission_user_entity_list[] = ['permission_id' => $task_review_permission_id, 'user_id' => $entity_id, 'entity_type' => 'TASK', 'entity_id' => $task->task_id]; } } PermissionUserEntity::insert($permission_user_entity_list); //create images if(!empty($task_images)) { foreach($task_images as $key => $file){ $this->saveTaskImage($task, $file); } } else{ TaskImage::insert(['task_id' => $task->task_id, 'image_name' => 'default-task-image-color.jpg']); } //create task assignees and sends notifications $this->createOrUpdateAssigneesAndNotify($task, $currentUser, $task_assignees_user_id_list); $activityHistory = UserActivityService::getDetailsForNewTaskAddedForParent($currentUser, $currentGroup, $task, 0); $tuitTransaction = $this->tuitService->triggerTuitCreditAction($currentUser, 'CREATION_OF_CUSTOM_TASKS', $activityHistory->activity_sub_details); $activityHistory = UserActivityService::getDetailsForNewTaskAddedForParent($currentUser, $currentGroup, $task, $tuitTransaction['tuit_credit']); $this->userActivityService->addActivityHistory($activityHistory->user_id, $activityHistory->group_id, $activityHistory->activity_details, $activityHistory->activity_sub_details, $activityHistory->side_effect_details); $taskDto = FilterTaskDTO::builder() ->user($currentUser) ->store($currentStore) ->group($currentGroup) ->shouldLoadAssigneeList(true) ->build(); $this->loadAdditionalInfo([$task], $taskDto); return $task; } private function createOrUpdateAssigneesAndNotify(Task $task, $parent_user, $assign_to_user_ids){ $childrenToNotify = []; $androidDeviceToken = []; $iosDeviceToken = []; foreach($assign_to_user_ids as $user_id){ $assignedUser = User::find($user_id); if(!$assignedUser){ Log::warning("user not found with $user_id"); continue; } TaskAssigned::insert([ 'user_id' => $user_id, 'task_id' => $task->task_id, 'group_id' => $parent_user->active_group_id, 'created_at' => date("Y-m-d H:i:s") ]); /* retrieve notification details - Start */ $assignedUser = User::find($user_id); $childrenToNotify[] = $assignedUser; if($assignedUser->device_type == 'android'){ $androidDeviceToken[] = $assignedUser->device_token; } else if($assignedUser->device_type == 'ios'){ $iosDeviceToken[] = $assignedUser->device_token; } /* retrieve notification details - End */ } //Notify $title = 'Task Assigned'; $msg = $task->task_title.' task has been assigned.'; $type = 'tasks'; foreach($childrenToNotify AS $child){ Helpers::notifyTaskAssignment($task, $parent_user, $assignedUser); } /* Notification Code - Start */ if(!empty($androidDeviceToken)){ Helpers::sendPushAndroid($androidDeviceToken, $title, $msg, $type, $task->task_id); } if(!empty($iosDeviceToken)){ Helpers::sendPushIOS($iosDeviceToken, $title, $msg, $type, $task->task_id); } Helpers::storeNotifications($parent_user->user_id, $assign_to_user_ids, $title, $msg, 'tasks', $task->task_id); } public function updateTask($currentUser, $task_obj, $new_task_details, $new_task_assignees_user_id_list, $new_task_images, $new_task_settings_details, $new_task_visibility_details, $new_task_review_permission_details, $currentGroup, $currentStore ){ $task_obj->task_title = $new_task_details['task_title'] != null ? $new_task_details['task_title'] : $task_obj->task_title; $task_obj->description = $new_task_details['description'] != null ? $new_task_details['description'] : $task_obj->description; $task_obj->task_sp = $new_task_details['task_sp'] != null ? $new_task_details['task_sp'] : $task_obj->task_sp; $task_obj->task_type = $new_task_details['task_type'] != null ? $new_task_details['task_type'] : $task_obj->task_type; $task_obj->product_id = $new_task_details['product_id'] != null ? $new_task_details['product_id'] : $task_obj->product_id; $task_obj->due_by = $new_task_details['due_by'] != null ? $new_task_details['due_by'] : $task_obj->due_by; $task_obj->task_status = $new_task_details['task_status'] != null ? $new_task_details['task_status'] : $task_obj->task_status; $task_obj->is_featured = $new_task_details['is_featured'] != null ? $new_task_details['is_featured'] : $task_obj->is_featured; $task_obj->save(); //saving images if($new_task_images != null && count($new_task_images) > 0){ TaskImage::where('task_id', $task_obj->task_id)->delete(); foreach($new_task_images as $key => $file){ $this->saveTaskImage($task_obj, $file); } } else{ $imageExist = TaskImage::where('task_id', $task_obj->task_id)->exists(); if(!$imageExist) { TaskImage::insert(['task_id' => $task_obj->task_id, 'image_name' => 'default-task-image-color.jpg']); } } if(isset($new_task_assignees_user_id_list['final'])){ $this->updateTaskAssignees($currentUser, $task_obj, $new_task_assignees_user_id_list); } else { //saving assignees $this->removeAndAddTaskAssignee($currentUser, $task_obj, $new_task_assignees_user_id_list); } //saving task settings $task_setting = $task_obj->taskSetting; if($task_setting == null){ $task_setting = TaskSetting::create(['task_id' => $task_obj->task_id]); } $task_setting->review_required = $new_task_settings_details['review_required'] != null ? $new_task_settings_details['review_required'] : $task_setting->review_required; $task_setting->repeate_after_days = $new_task_settings_details['repeate_after_days'] != null ? $new_task_settings_details['repeate_after_days'] : $task_setting->repeate_after_days; $task_setting->save(); $taskDto = FilterTaskDTO::builder() ->user($currentUser) ->store($currentStore) ->group($currentGroup) ->shouldLoadAssigneeList(true) ->build(); $this->loadAdditionalInfo([$task_obj], $taskDto); $task_review_allowed_to_type_arr = isset($task_settings_details['task_review_allowed_to_type_arr']) ? $task_settings_details['task_review_allowed_to_type_arr'] : ['PARENTS_OR_FOSTER_AGENT']; $this->saveTaskReviewAllowed($task_obj->task_id, $task_setting->task_settings_id, $task_review_allowed_to_type_arr); //saving task visibility //not changing saving visibility for edit task } public function updateTaskAssignees($currentUser, $task_obj, $new_task_assignees_user_id_list){ $childrenIdsToNotify = []; // Retrieve the current list of task assignees from the database $current_task_assignees = TaskAssigned::where('task_id', $task_obj->task_id) ->pluck('user_id') ->toArray(); // Get the final list of assignees from the input $final_assignees = $new_task_assignees_user_id_list['final']; // Determine the assignees to be added and removed $assignees_to_add = array_diff($final_assignees, $current_task_assignees); $assignees_to_remove = array_diff($current_task_assignees, $final_assignees); // Add new assignees foreach($assignees_to_add as $user_id){ $childrenIdsToNotify[] = $user_id; if(!TaskAssigned::isTaskAssignmentPresent($user_id, $task_obj->task_id)){ TaskAssigned::insert([ 'user_id' => $user_id, 'task_id' => $task_obj->task_id, 'group_id' => $currentUser->active_group_id, 'created_at' => date("Y-m-d H:i:s") ]); } } // Remove assignees that are no longer in the final list foreach($assignees_to_remove as $user_id){ if(TaskAssigned::isTaskAssignmentPresent($user_id, $task_obj->task_id)){ TaskAssigned::where("user_id", $user_id) ->where("task_id", $task_obj->task_id) ->delete(); } } /* Notification Code - Start */ $androidDeviceToken = $iosDeviceToken = []; foreach($childrenIdsToNotify as $child_id){ $assignedUser = User::find($child_id); Helpers::notifyTaskAssignment($task_obj, $currentUser, $assignedUser); if($assignedUser->device_type == 'android'){ $androidDeviceToken[] = $assignedUser->device_token; } else if($assignedUser->device_type == 'ios'){ $iosDeviceToken[] = $assignedUser->device_token; } } $title = 'Task Assigned'; $msg = $task_obj->task_title.' task has been assigned.'; $type = 'tasks'; if(!empty($androidDeviceToken)){ Helpers::sendPushAndroid($androidDeviceToken, $title, $msg, $type, $task_obj->task_id); } if(!empty($iosDeviceToken)){ Helpers::sendPushIOS($iosDeviceToken, $title, $msg, $type, $task_obj->task_id); } if(!empty($childrenIdsToNotify)){ Helpers::storeNotifications($currentUser->user_id, $childrenIdsToNotify, $title, $msg, 'tasks', $task_obj->task_id); } } public function removeAndAddTaskAssignee($currentUser, $task_obj, $new_task_assignees_user_id_list){ $childrenIdsToNotify = []; //update assignee if(isset($new_task_assignees_user_id_list['add'])){ foreach($new_task_assignees_user_id_list['add'] as $user_id){ $childrenIdsToNotify[] = $user_id; if(!TaskAssigned::isTaskAssignmentPresent($user_id, $task_obj->task_id)) TaskAssigned::insert([ 'user_id' => $user_id, 'task_id' => $task_obj->task_id, 'group_id' => $currentUser->active_group_id, 'created_at' => date("Y-m-d H:i:s") ]); } } if(isset($new_task_assignees_user_id_list['remove'])){ foreach($new_task_assignees_user_id_list['remove'] as $user_id){ if(TaskAssigned::isTaskAssignmentPresent($user_id, $task_obj->task_id)) TaskAssigned::where("user_id", $user_id) ->where("task_id", $task_obj->task_id) ->delete(); } } /* Notification Code - Start */ $androidDeviceToken = $iosDeviceToken = []; foreach($childrenIdsToNotify AS $child_id){ $assignedUser = User::find($child_id); Helpers::notifyTaskAssignment($task_obj, $currentUser, $assignedUser); if($assignedUser->device_type == 'android'){ $androidDeviceToken[] = $assignedUser->device_token; } else if($assignedUser->device_type == 'ios'){ $iosDeviceToken[] = $assignedUser->device_token; } } $title = 'Task Assigned'; $msg = $task_obj->task_title.' task has been assigned.'; $type = 'tasks'; if(!empty($androidDeviceToken)){ Helpers::sendPushAndroid($androidDeviceToken, $title, $msg, $type, $task_obj->task_id); } if(!empty($iosDeviceToken)){ Helpers::sendPushIOS($iosDeviceToken, $title, $msg, $type, $task_obj->task_id); } if(!empty($childrenIdsToNotify)) Helpers::storeNotifications($currentUser->user_id, $childrenIdsToNotify, $title, $msg, 'tasks', $task_obj->task_id); } private function saveTaskImage($task, $image_file){ $image_name = rand().time().'.'.$image_file->getClientOriginalExtension(); // Save thumbnail image $img = Image::make($image_file->getRealPath()); $img->resize(200, 200, function ($constraint) { $constraint->aspectRatio(); })->save(public_path('task_images/thumb/').$image_name); // Save original size image $image_file->move(public_path('task_images'), $image_name); TaskImage::insert(['task_id' => $task->task_id, 'image_name' => $image_name]); } private function loadAdditionalInfo($tasks, $filter){ $taskIdToTaskMap = []; foreach($tasks AS $task){ $taskIdToTaskMap[$task->task_id] = $task; } if($filter->shouldLoadAssigneeLists()){ $taskAssigneeFilterDto = TaskAssigneeFilterDTO::builder() ->copyFrom($filter) ->taskIds(array_keys($taskIdToTaskMap)) ->build(); $task_assignees = $this->taskRepository->getTaskAssigneesInGroup($taskAssigneeFilterDto); foreach($task_assignees AS $task_assignee){ $task = $taskIdToTaskMap[$task_assignee->task_id]; $task->addTaskAssignee($task_assignee); } } } public function getAssignedTask(User $user, Store $currentStore, Group $currentGroup, $task_id){ $filter = TaskAssigneeFilterDTO::builder() ->user($user)->store($currentStore)->group($currentGroup) ->taskIds([$task_id])->build(); $taskAssignedList = $this->taskRepository->getTaskAssignedForUser($filter); if(count($taskAssignedList) > 0){ return $taskAssignedList[0]; } return null; } public function isTaskVisibleForChild(User $user, Task $task){ if($task->taskSetting != null){ $taskSetting = $task->taskSetting; Log::debug('task visible_to: '. $taskSetting->visible_to); switch($taskSetting->visible_to){ case 'GLOBAL': return true; break; case 'GLOBAL_FOR_PARENT_AND_CHILD': return true; break; case 'ZIPCODE_PARENT_AND_CHILD': $user_zipcode = $user->userAddress != null ? $user->userAddress->zipcode : null; $user_country = $user->userAddress != null ? $user->userAddress->country : null; if($user_zipcode != null){ $zipcodeVisibility = $taskSetting->taskVisibility()->where('entity_type', 'ZIPCODE') ->where('entity_value', $user_zipcode)->first(); $countryVisibility = $taskSetting->taskVisibility()->where('entity_type', 'COUNTRY') ->where('entity_value', $user_country)->first(); if($zipcodeVisibility != null && $countryVisibility != null) return true; } break; case 'COUNTRY_PARENT_AND_CHILD': $user_country = $user->userAddress != null ? $user->userAddress->country : null; if($user_country != null){ $taskVisibility = $taskSetting->taskVisibility()->where('entity_type', 'COUNTRY') ->where('entity_value', $user_country)->first(); if($taskVisibility != null) return true; } break; } } return false; } public function cloneTasksAndRewards($tasks){ try { //starting the db transaction DB::beginTransaction(); // Perform your database operations here // For example, inserting/updating/deleting records $newTasks = []; foreach($tasks AS $task){ if($this->alreadyClonedToday($task)){ Log::debug("task with task_id: {$task->task_id} already cloned today"); continue; } $newTasks [] = $this->cloneTaskAndReward($task); } // If everything is successful, commit the transaction DB::commit(); return $newTasks; } catch (\Exception $e) { // If any error occurs, rollback the transaction to revert changes DB::rollBack(); Log::error("Error while clonning tasks and associated rewards, rolling back the transaction. Message: ". $e->getMessage()); Log::error($e->getTraceAsString()); return null; } } public function cloneTaskAndReward($task, $shouldCloneReward = true){ $newProduct = null; if($shouldCloneReward){ $product = $task->product; $newProduct = $this->cloneReward($product); } //clone task $newTask = $task->cloneTask($newProduct); $taskSetting = $task->taskSetting; if($taskSetting != null){ $newTaskSetting = $task->taskSetting->cloneTaskSetting($newTask); $taskVisibilityList = $taskSetting->taskVisibility; if($taskVisibilityList != null && count($taskVisibilityList) > 0){ foreach($taskVisibilityList AS $visibility){ $visibility->cloneTaskVisibility($newTaskSetting); } } } $taskAssignedList = TaskAssigned::where('task_id', $task->task_id)->get(); if($taskAssignedList != null && count($taskAssignedList) > 0){ foreach($taskAssignedList AS $taskAssigned){ $taskAssigned->cloneTaskAssignee($newTask); } } if($taskSetting != null){ $taskReviewAllowedList = TaskReviewAllowed::where('task_settings_id', $taskSetting->task_settings_id)->get(); if($taskReviewAllowedList != null){ foreach($taskReviewAllowedList AS $taskReviewAllowed){ $taskReviewAllowed->cloneTaskReviewAllowed($newTaskSetting); } } } $images = $task->images; if($images != null && count($images) > 0){ foreach($images AS $image){ $image->cloneTaskImage($newTask); } } return $newTask; } public function cloneReward($product){ //cloning product first; $newProduct = null; if($product != null){ $productSetting = $product->productSetting; $newProduct = $product->cloneProduct(); if($productSetting != null){ $newProductSetting = $productSetting->cloneRewardSetting($newProduct); $rewardVisibilityList = $productSetting->rewardVisibility; if($rewardVisibilityList != null && count($rewardVisibilityList) > 0){ foreach($rewardVisibilityList AS $visibility){ $visibility->cloneRewardVisibility($newProductSetting); } } } $images = $product->images; if($images != null && count($images) > 0){ foreach($images AS $image){ $image->cloneProductImage($newProduct); } } $customFields = $product->customFields; $newCustomFields = []; foreach($customFields AS $customField){ $newCustomField = $customField->cloneCustomField('PRODUCT', $newProduct->product_id); $newCustomFields[] = $newCustomField; } } return $newProduct; } public function alreadyClonedToday($task){ $task = Task::where('parent_task_id', $task->task_id) ->whereRaw("DATE(created_at) = DATE(CURRENT_DATE)") ->first(); return $task != null; } public function saveTaskReviewAllowed($task_id, $task_settings_id, $task_review_allowed_to_type_arr) { $task_review_allowed_to_type_arr = $task_review_allowed_to_type_arr == null ? [] : $task_review_allowed_to_type_arr; // Retrieve existing entries $tasks_review_allowed_list = TaskReviewAllowed::where('task_id', $task_id) ->where('task_settings_id', $task_settings_id) ->pluck('review_allowed_to_type') ->toArray(); if($tasks_review_allowed_list == null) $tasks_review_allowed_list = []; // Determine entries to be added $toBeAdded = array_diff($task_review_allowed_to_type_arr, $tasks_review_allowed_list); // Determine entries to be deleted $toBeDeleted = array_diff($tasks_review_allowed_list, $task_review_allowed_to_type_arr); // Add new entries if(!empty($toBeAdded)){ foreach ($toBeAdded as $review_allowed_to_type) { TaskReviewAllowed::create([ 'task_id' => $task_id, 'task_settings_id' => $task_settings_id, 'review_allowed_to_type' => $review_allowed_to_type, ]); } } if(!empty($toBeDeleted)){ // Delete old entries TaskReviewAllowed::where('task_id', $task_id) ->where('task_settings_id', $task_settings_id) ->whereIn('review_allowed_to_type', $toBeDeleted) ->delete(); } } } ?>